#include <lib/holyhttp.h>
#include <utils/string.h>
#include <utils/dbapi.h>
#include "cgi.h"
#include "guest.h"

static db_table_t guests = {0};
static db_col_t guest_cols[GUEST_COL_NUM] = {
    DB_COL_SET_STR_UNQ(GUEST_COL_NAME, "name", GUEST_NAME_LEN),
    DB_COL_SET_STR(GUEST_COL_KEY, "key", GUEST_KEY_LEN),
    DB_COL_SET_STR(GUEST_COL_CREATED_TIME, "created time", TIME_STR_LEN),
};

int get_guest_id(char *name, char *key)
{
    db_row_t *row = NULL;
    db_value_t values[GUEST_COL_NUM] = {0};
    // check guest
    row = guests.find(&guests, GUEST_COL_NAME, (db_value_t)name);
    if (row) {
        int ret = 0;
        if (0 == strcmp(key, row->values[GUEST_COL_KEY].s)) {
            ret = row->id;
        }
        free(row);
        return ret;
    }
    // new guest
    values[GUEST_COL_NAME].s = name;
    values[GUEST_COL_KEY].s = key;
    values[GUEST_COL_CREATED_TIME].s = get_datetime_str();
    return guests.add(&guests, values);
}

int get_guest_name(int id, char *name, u32 len)
{
    db_row_t *row = guests.get(&guests, id);
    if (row) {
        strncpy(name, row->values[GUEST_COL_NAME].s, len-1);
        free(row);
        return 1;
    }
    return 0;
}

void init_guest(void)
{
    db_table_init(DEF_SQLITE3_DB, &guests, "guest", guest_cols, ARRAY_SIZE(guest_cols));
}

